<template>
    <el-container class="snake-game-container">
      <el-header>
        <h2>贪吃蛇小游戏</h2>
      </el-header>
      <el-main>
        <div class="game-area">
          <canvas id="gameCanvas" width="400" height="400"></canvas>
        </div>
        <el-row justify="center" class="score-display">
          <el-tag type="success">分数: {{ score }}</el-tag>
        </el-row>
        <el-row justify="center" class="controls">
          <el-button type="primary" @click="startGame">开始游戏</el-button>
          <el-button type="danger" @click="resetGame">重置游戏</el-button>
        </el-row>
      </el-main>
    </el-container>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  
  const canvas = ref(null);
  const ctx = ref(null);
  const box = 20; // 每个格子的大小
  let snake = ref([{ x: 9 * box, y: 10 * box }]); // 初始蛇的位置
  let direction = ref(null); // 蛇的方向
  let food = ref({
    x: Math.floor(Math.random() * 20) * box,
    y: Math.floor(Math.random() * 20) * box,
  });
  let score = ref(0);
  let gameInterval = null;
  
  // 初始化游戏
  const initGame = () => {
    canvas.value = document.getElementById('gameCanvas');
    ctx.value = canvas.value.getContext('2d');
  };
  
  // 开始游戏
  const startGame = () => {
    if (gameInterval) clearInterval(gameInterval);
    gameInterval = setInterval(drawGame, 100);
  };
  
  // 重置游戏
  const resetGame = () => {
    clearInterval(gameInterval);
    snake.value = [{ x: 9 * box, y: 10 * box }];
    direction.value = null;
    food.value = {
      x: Math.floor(Math.random() * 20) * box,
      y: Math.floor(Math.random() * 20) * box,
    };
    score.value = 0;
    drawGame();
  };
  
  // 监听键盘事件
  document.addEventListener('keydown', (event) => {
    if (event.key === 'ArrowUp' && direction.value !== 'DOWN') direction.value = 'UP';
    else if (event.key === 'ArrowDown' && direction.value !== 'UP') direction.value = 'DOWN';
    else if (event.key === 'ArrowLeft' && direction.value !== 'RIGHT') direction.value = 'LEFT';
    else if (event.key === 'ArrowRight' && direction.value !== 'LEFT') direction.value = 'RIGHT';
  });
  
  // 绘制游戏
  const drawGame = () => {
    // 绘制背景
    ctx.value.fillStyle = '#fff';
    ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
  
    // 绘制蛇
    for (let i = 0; i < snake.value.length; i++) {
      ctx.value.fillStyle = i === 0 ? '#4caf50' : '#8bc34a';
      ctx.value.fillRect(snake.value[i].x, snake.value[i].y, box, box);
      ctx.value.strokeStyle = '#fff';
      ctx.value.strokeRect(snake.value[i].x, snake.value[i].y, box, box);
    }
  
    // 绘制食物
    ctx.value.fillStyle = '#f44336';
    ctx.value.fillRect(food.value.x, food.value.y, box, box);
  
    // 更新蛇的位置
    let snakeX = snake.value[0].x;
    let snakeY = snake.value[0].y;
  
    if (direction.value === 'UP') snakeY -= box;
    if (direction.value === 'DOWN') snakeY += box;
    if (direction.value === 'LEFT') snakeX -= box;
    if (direction.value === 'RIGHT') snakeX += box;
  
    // 检查是否吃到食物
    if (snakeX === food.value.x && snakeY === food.value.y) {
      score.value++;
      food.value = {
        x: Math.floor(Math.random() * 20) * box,
        y: Math.floor(Math.random() * 20) * box,
      };
    } else {
      snake.value.pop(); // 移除蛇尾
    }
  
    // 添加新的蛇头
    const newHead = { x: snakeX, y: snakeY };
  
    // 检查碰撞
    if (
      snakeX < 0 ||
      snakeX >= canvas.value.width ||
      snakeY < 0 ||
      snakeY >= canvas.value.height ||
      collision(newHead, snake.value)
    ) {
      clearInterval(gameInterval);
      ElMessage.error(`游戏结束！您的分数是：${score.value}`);
    }
  
    snake.value.unshift(newHead);
  };
  
  // 检查碰撞
  const collision = (head, array) => {
    for (let i = 0; i < array.length; i++) {
      if (head.x === array[i].x && head.y === array[i].y) {
        return true;
      }
    }
    return false;
  };
  
  // 初始化
  onMounted(() => {
    initGame();
    drawGame();
  });
  </script>
  
  <style scoped>
  .snake-game-container {
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
    text-align: center;
  }
  
  .game-area {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .score-display {
    margin-bottom: 20px;
  }
  
  .controls {
    margin-top: 10px;
  }
  </style>